package com.gwd.task.controller;

import com.gwd.task.group.GroupInsert;
import com.gwd.task.group.GroupLogin;
import com.gwd.task.group.GroupUpdate;
import com.gwd.task.model.CallResultMsg;
import com.gwd.task.model.PageUtils;
import com.gwd.task.model.UserDTO;
import com.gwd.task.services.UserServer;
import com.gwd.task.untils.JwtUtil;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author zhiyongming
 * @date 2020/11/11 13:43
 */

@RestController
@RequestMapping(value = "/v1/user")
public class UserController {
    @Resource
    private UserServer userServer;

    @PostMapping(value = "/login")
    public CallResultMsg<?> login(@RequestBody @Validated({GroupLogin.class}) UserDTO dto) {
        return userServer.login(dto);
    }

    @GetMapping(value = "/info")
    public CallResultMsg<?> getInfo(@RequestParam(value = "token") String token, @RequestAttribute("userId") Long id) {
        return CallResultMsg.success(userServer.findById(id));
    }

    @PostMapping(value = "/logout")
    public CallResultMsg<?> logout(@RequestAttribute("userId") Long id) {
        JwtUtil.removeMap(id);
        return CallResultMsg.success();
    }

    @PostMapping(value = "/add")
    public CallResultMsg<?> add(@RequestBody @Validated({GroupInsert.class}) UserDTO dto) {
        userServer.save(dto);
        return CallResultMsg.success();
    }

    @PutMapping(value = "/edit")
    public void edit(@RequestBody @Validated({GroupUpdate.class}) UserDTO dto) {
        userServer.save(dto);
    }

    @PutMapping(value = "/reset")
    public void reset(@RequestBody UserDTO dto, @RequestAttribute("userId") Long id) {
        userServer.reset(id, dto.getPassword());
    }

    @DeleteMapping(value = "/remove/{id}")
    public void remove(@PathVariable(value = "id") Long id) {
        userServer.remove(id);
    }

    @PutMapping(value = "/active/{id}")
    public void active(@PathVariable(value = "id") Long id) {
        userServer.active(id);
    }

    @GetMapping(value = "/findByPage")
    public PageUtils findByPage(UserDTO dto, PageUtils page) {
        return userServer.findByPage(dto, page);
    }

    @GetMapping(value = "/findAll")
    public CallResultMsg<?> findAll(UserDTO dto) {
        return CallResultMsg.success(userServer.findAll(dto));
    }

    @GetMapping(value = "/findByGroup")
    public List<UserDTO> findByGroup(@RequestParam(value = "groupId") Long groupId) {
        return userServer.findByGroup(groupId);
    }
}
